package cn.javabb.web.controller;

import cn.javabb.common.model.ResponseModel;
import cn.javabb.common.utils.RequestUtil;
import cn.javabb.core.base.BaseController;
import cn.javabb.core.entity.sys.UserDO;
import cn.javabb.core.model.LoginType;
import cn.javabb.core.service.sys.UserService;
import cn.javabb.core.shiro.UserToken;
import cn.javabb.log.action.UserAction;
import cn.javabb.log.annotation.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/** 前台登陆
 * @Author QINB imqinbao@163.com
 * @CreateDate 2019/1/13/013 23:53
 * @Since V1.0
 */
@Slf4j
@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @GetMapping("/loginForm/login")
    public String popLoginPage(HttpSession session){
        session.setAttribute("historyUrl", RequestUtil.getReferer());
        return "web/view/login/loginForm";
    }
    @GetMapping("/loginForm/register")
    public String popRegPage(){
        return "web/view/login/registerForm";
    }
    /**
     * 登录
     */
    @ResponseBody
    @PostMapping("/login")
    @Log(key= UserAction.ADMIN_USER_LOGIN,action = UserAction.class)
    public Object doLogin(String username, String password, String code, HttpServletRequest request) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ResponseModel.Failure("账号密码不能为空");
        }
        log.info("准备登陆用户  =>  {}", username);
        /*
         * if (!CaptchaUtil.ver(code, request)) { CaptchaUtil.clear(request); return
         * ResponseModel.Failure("验证码不正确"); }
         */
        UserToken token = new UserToken(username, password, LoginType.USER.getDesc());
        // 获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();
        try {
            log.info("对用户[" + username + "]进行登录验证..验证开始");
            currentUser.login(token);
            log.info("对用户[" + username + "]进行登录验证..验证通过");
        } catch (IncorrectCredentialsException ice) {
            return ResponseModel.Failure("密码错误");
        } catch (UnknownAccountException uae) {
            return ResponseModel.Failure("账号不存在");
        } catch (LockedAccountException e) {
            return ResponseModel.Failure("账号被锁定");
        } catch (ExcessiveAttemptsException eae) {
            return ResponseModel.Failure("操作频繁，请稍后再试");
        }
        // 验证是否登录成功
        if (currentUser.isAuthenticated()) {
            log.info("用户[" + username + "]登录认证通过");
            return ResponseModel.Success("登录成功");
            // return "redirect:/index";
        } else {
            token.clear();
            return ResponseModel.Failure("登陆失败");
        }

    }

    @GetMapping("/logout")
    public String logout(RedirectAttributes redirectAttributes) {
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        SecurityUtils.getSubject().logout();
        //
        //redirectAttributes.addFlashAttribute("message", "您已安全退出");
        return "redirect:/";
    }
    @PostMapping("/register")
    @ResponseBody
    public Object register(UserDO user,String userPwd){
        if(userService.queryUsernameRepeat(user.getUserName())){
            return ResponseModel.Failure("用户名重复");
        }
        UserDO newUser = userService.addUser(user,userPwd);
        if(null != newUser){
            return ResponseModel.Success("注册成功");
        }

        return ResponseModel.Failure("注册失败");
    }
}
